#include <iostream>
#include <pthread.h>
#include <unistd.h>
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//全局条件变量
//pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//全局锁
using namespace std;
 int i = 100;
 class lock
 {
  public:
  lock( pthread_mutex_t* mutex)
  :mutex_(mutex)
  {
    pthread_mutex_lock(mutex_);
  }
  ~lock()
  {
    pthread_mutex_unlock(mutex_);
  }
  private:
  pthread_mutex_t * mutex_;
 };
void *handler(void *args)
{
    pthread_mutex_t*mutex=static_cast<pthread_mutex_t*>(args);//参数类型转换
    // int a=10;
    while (true)
    {
        if(i>0)
        {
          lock l1(mutex);
      //  pthread_mutex_lock(mutex);//上锁
        pthread_cond_wait(&cond,mutex);//到条件变量里的等待队列里等，同时解锁
        if (i > 0)
        {
            //sleep(1);
            cout << i-- << endl;
            //sleep(1);
           // printf("Thread stack addresss is : %p\n", &i); // 打印a变量地址
           printf("thread id is: 0x%x\n",pthread_self());
        }
        //pthread_mutex_unlock(mutex);//解锁
        }
        else
        break;

    }
  
    return nullptr;
}
int main()
{
  pthread_mutex_t mutex;//锁变量创建
    pthread_mutex_init(&mutex,nullptr);//锁初始化
    pthread_t tid[3];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(tid + i, nullptr, handler, &mutex);
    }
    while(true)
    {
      pthread_cond_signal(&cond);
    sleep(1);
    }
    for (int i = 0; i < 3; i++)
    {
        pthread_join(tid[i], nullptr);
    }
  pthread_mutex_destroy(&mutex);//锁销毁
    return 0;
}